import React from 'react';
import {TabBar} from 'antd-mobile';
import Icon from '@components/icon';
import Home from '@container/home';
import Center from '@container/center';
import {fetch} from '@utils/Fetch';

class App extends React.PureComponent {
  constructor(props) {
    super(props);
  }

  state = {
    selectedTab: 'home',
    hidden: false
  };

  componentDidMount() {
    this.fCheck();
    const {history, location} = this.props;
    const {selectedTab} = this.state;
    if (location.pathname === '/') {
      history.replace(`/${selectedTab}`);
    }
  }

  fCheck = () => {
    const {history} = this.props;
    fetch('/api/user/check').get()
      .success(res => this.setState({user: res.content}))
      .error(() => history.replace('/login'));
  };
  tabs = () => {
    return [
      {title: '首页', tab: 'home', icon: 'home', component: Home},
      {title: '我的', tab: 'center', icon: 'center', component: Center}
    ];
  };
  fPress = (tab) => {
    this.props.history.replace(`/${tab}`);
    this.setState({selectedTab: tab});
  };
  fGetTab = () => {
    const {selectedTab} = this.state;
    const {history, location} = this.props;
    return this.tabs().map(t => (
      <TabBar.Item title={t.title}
                   key={t.tab}
                   icon={<Icon type={t.icon} style={{fontSize: '22px'}} />}
                   selectedIcon={<Icon type={t.icon} style={{fontSize: '22px'}} />}
                   selected={selectedTab === t.tab}
                   onPress={() => this.fPress(t.tab)}
      >
        {React.createElement(t.component, {history, location})}
      </TabBar.Item>
    ));
  };

  render() {
    return (
      <TabBar unselectedTintColor='#949494'
              tintColor='#33A3F4'
              barTintColor='white'
              hidden={this.state.hidden}
      >
        {this.fGetTab()}
      </TabBar>
    )
  }
}

export default App;
